<!DOCTYPE html>
<html lang="" xml:lang="">
  <head>
    <title>Hypothesis testing</title>
    <meta charset="utf-8" />
    <meta name="author" content="datasciencebox.org" />
    <script src="libs/header-attrs/header-attrs.js"></script>
    <link href="libs/font-awesome/css/all.css" rel="stylesheet" />
    <link href="libs/font-awesome/css/v4-shims.css" rel="stylesheet" />
    <link href="libs/panelset/panelset.css" rel="stylesheet" />
    <script src="libs/panelset/panelset.js"></script>
    <link rel="stylesheet" href="../xaringan-themer.css" type="text/css" />
    <link rel="stylesheet" href="../slides.css" type="text/css" />
  </head>
  <body>
    <textarea id="source">
class: center, middle, inverse, title-slide

.title[
# Hypothesis testing
]
.subtitle[
## <br><br> Data Science in a Box
]
.author[
### <a href="https://datasciencebox.org/">datasciencebox.org</a>
]

---





layout: true
  
&lt;div class="my-footer"&gt;
&lt;span&gt;
&lt;a href="https://datasciencebox.org" target="_blank"&gt;datasciencebox.org&lt;/a&gt;
&lt;/span&gt;
&lt;/div&gt; 

---



class: middle

# Hypothesis testing for a single proportion

---

## Packages


```r
library(tidyverse)
library(tidymodels)
```


---

## Organ donors

People providing an organ for donation sometimes seek the help of a special "medical consultant". These consultants assist the patient in all aspects of the surgery, with the goal of reducing the possibility of complications during the medical procedure and recovery. Patients might choose a consultant based in part on the historical complication rate of the consultant's clients. 

One consultant tried to attract patients by noting that the average complication rate for liver donor surgeries in the US is about 10%, but her clients have only had 3 complications in the 62 liver donor surgeries she has facilitated. She claims this is strong evidence that her work meaningfully contributes to reducing complications (and therefore she should be hired!).

---

## Data




```r
organ_donor %&gt;%
  count(outcome)
```

```
## # A tibble: 2 × 2
##   outcome             n
##   &lt;chr&gt;           &lt;int&gt;
## 1 complication        3
## 2 no complication    59
```

---

## Parameter vs. statistic

A **parameter** for a hypothesis test is the "true" value of interest. We typically estimate the parameter using a **sample statistic** as a **point estimate**.

`\(p~\)`: true rate of complication

`\(\hat{p}~\)`: rate of complication in the sample = `\(\frac{3}{62}\)` = 
0.048

---

## Correlation vs. causation

.question[
Is it possible to assess the consultant's claim using the data?
]

--

No. The claim is that there is a causal connection, but the data are observational.
For example, maybe patients who can afford a medical consultant can afford better medical care, which can also lead to a lower complication rate.

While it is not possible to assess the causal claim, it is still possible to test for an association using these data. For this question we ask, could the low complication rate of `\(\hat{p}\)` = 0.048 be due to chance?

---

## Two claims

- **Null hypothesis:** "There is nothing going on"

Complication rate for this consultant is no different than the US average of 10%

--

- **Alternative hypothesis:** "There is something going on"

Complication rate for this consultant is **lower** than the US average of 10%

---

## Hypothesis testing as a court trial

- **Null hypothesis**, `\(H_0\)`: Defendant is innocent

- **Alternative hypothesis**, `\(H_A\)`: Defendant is guilty

--

- **Present the evidence:** Collect data

--

- **Judge the evidence:** "Could these data plausibly have happened by chance if the null hypothesis were true?"
    * Yes: Fail to reject `\(H_0\)`
    * No: Reject `\(H_0\)`
    
---

## Hypothesis testing framework

- Start with a null hypothesis, `\(H_0\)`, that represents the status quo

- Set an alternative hypothesis, `\(H_A\)`, that represents the research question, i.e. what we’re testing for

- Conduct a hypothesis test under the assumption that the null hypothesis is true and calculate a **p-value** (probability of observed or more extreme outcome given that the null hypothesis is true)
    - if the test results suggest that the data do not provide convincing evidence for the alternative hypothesis, stick with the null hypothesis
    - if they do, then reject the null hypothesis in favor of the alternative

---

## Setting the hypotheses

.question[
Which of the following is the correct set of hypotheses?
]

(a) `\(H_0: p = 0.10\)`; `\(H_A: p \ne 0.10\)` &lt;br&gt;

(b) `\(H_0: p = 0.10\)`; `\(H_A: p &gt; 0.10\)` &lt;br&gt;

(c) `\(H_0: p = 0.10\)`; `\(H_A: p &lt; 0.10\)` &lt;br&gt;

(d) `\(H_0: \hat{p} = 0.10\)`; `\(H_A: \hat{p} \ne 0.10\)` &lt;br&gt;

(e) `\(H_0: \hat{p} = 0.10\)`; `\(H_A: \hat{p} &gt; 0.10\)` &lt;br&gt;

(f) `\(H_0: \hat{p} = 0.10\)`; `\(H_A: \hat{p} &lt; 0.10\)` &lt;br&gt;

---

## Simulating the null distribution

Since `\(H_0: p = 0.10\)`, we need to simulate a null distribution where the probability of success (complication) for each trial (patient) is 0.10.

.question[
Describe how you would simulate the null distribution for this study using a bag of chips. How many chips? What colors? What do the colors indicate? How many draws? &lt;b&gt;With replacement&lt;/b&gt; or &lt;b&gt;without replacement&lt;/b&gt;?
]

---

## What do we expect?

.question[
When sampling from the null distribution, what is the expected proportion of success (complications)?
]

---

## Simulation #1


```
## sim1
##    complication no complication 
##               3              59
```

```
## [1] 0.0483871
```

&lt;img src="u4-d12-hypothesis-testing_files/figure-html/unnamed-chunk-5-1.png" width="50%" style="display: block; margin: auto;" /&gt;

---

## Simulation #2


```
## sim2
##    complication no complication 
##               9              53
```

```
## [1] 0.1451613
```

&lt;img src="u4-d12-hypothesis-testing_files/figure-html/unnamed-chunk-6-1.png" width="50%" style="display: block; margin: auto;" /&gt;

---

## Simulation #3



```
## sim3
##    complication no complication 
##               8              54
```

```
## [1] 0.1290323
```

&lt;img src="u4-d12-hypothesis-testing_files/figure-html/unnamed-chunk-7-1.png" width="50%" style="display: block; margin: auto;" /&gt;

---

## This is getting boring...

We need a way to automate this process!

---

## Using tidymodels to generate the null distribution

.small[

```r
null_dist &lt;- organ_donor %&gt;%
  specify(response = outcome, success = "complication") %&gt;%
  hypothesize(null = "point", p = c("complication" = 0.10, "no complication" = 0.90)) %&gt;% 
  generate(reps = 100, type = "simulate") %&gt;% 
  calculate(stat = "prop")
```
]


```
## Response: outcome (factor)
## Null Hypothesis: point
## # A tibble: 100 × 2
##   replicate  stat
##       &lt;dbl&gt; &lt;dbl&gt;
## 1         1 0.161
## 2         2 0.081
## 3         3 0.161
## 4         4 0.145
## 5         5 0.097
## 6         6 0.145
## # … with 94 more rows
```


---

## Visualizing the null distribution

.question[
What would you expect the center of the null distribution to be?
]

--


```r
ggplot(data = null_dist, mapping = aes(x = stat)) +
  geom_histogram(binwidth = 0.01) +
  labs(title = "Null distribution")
```

&lt;img src="u4-d12-hypothesis-testing_files/figure-html/unnamed-chunk-10-1.png" width="40%" style="display: block; margin: auto;" /&gt;


---

## Calculating the p-value, visually

.question[
What is the p-value, i.e. in what % of the simulations was the simulated sample proportion at least as extreme as the observed sample proportion?
]

&lt;img src="u4-d12-hypothesis-testing_files/figure-html/unnamed-chunk-11-1.png" width="50%" style="display: block; margin: auto;" /&gt;

---

## Calculating the p-value, directly


```r
null_dist %&gt;%
  filter(stat &lt;= (3/62)) %&gt;%
  summarise(p_value = n()/nrow(null_dist))
```

```
## # A tibble: 1 × 1
##   p_value
##     &lt;dbl&gt;
## 1    0.12
```


---

## Significance level

We often use 5% as the cutoff for whether the p-value is low enough that the data are unlikely to have come from the null model. This cutoff value is called the **significance level**, `\(\alpha\)`.

- If p-value &lt; `\(\alpha\)`, reject `\(H_0\)` in favor of `\(H_A\)`: The data provide convincing evidence for the alternative hypothesis.

- If p-value &gt; `\(\alpha\)`, fail to reject `\(H_0\)` in favor of `\(H_A\)`: The data do not provide convincing evidence for the alternative hypothesis.

---

## Conclusion

.question[
What is the conclusion of the hypothesis test?
]

--

Since the p-value is greater than the significance level, we fail to reject the null hypothesis. 
These data do not provide convincing evidence that this consultant incurs a lower complication rate than 10% (overall US complication rate).

---

## Let's get real

- 100 simulations is not sufficient

- We usually simulate around 15,000 times to get an accurate distribution, but we'll do 1,000 here for efficiency.

---

## Run the test

.small[

```r
null_dist &lt;- organ_donor %&gt;%
  specify(response = outcome, success = "complication") %&gt;%
  hypothesize(null = "point", p = c("complication" = 0.10, "no complication" = 0.90)) %&gt;% 
  generate(reps = 1000, type = "simulate") %&gt;% 
  calculate(stat = "prop")
```
]

---

## Visualize and calculate

.small[

```r
ggplot(data = null_dist, mapping = aes(x = stat)) +
  geom_histogram(binwidth = 0.01) +
  geom_vline(xintercept = 3/62, color = "red")
```

&lt;img src="u4-d12-hypothesis-testing_files/figure-html/unnamed-chunk-14-1.png" width="30%" style="display: block; margin: auto;" /&gt;

```r
null_dist %&gt;%
  filter(stat &lt;= 3/62) %&gt;%
  summarise(p_value = n()/nrow(null_dist))
```

```
## # A tibble: 1 × 1
##   p_value
##     &lt;dbl&gt;
## 1   0.124
```
]

---

class: middle

# One vs. two sided hypothesis tests

---

## Types of alternative hypotheses

- One sided (one tailed) alternatives: The parameter is hypothesized to be less than or greater than the null value, &lt; or &gt;

--

- Two sided (two tailed) alternatives: The parameter is hypothesized to be not equal to the null value, `\(\ne\)`
    - Calculated as two times the tail area beyond the observed sample statistic
    - More objective, and hence more widely preferred
    
--

.question[
Average systolic blood pressure of people with 
Stage 1 Hypertension is 150 mm Hg. 
Suppose we want to use a hypothesis test to evaluate whether a new blood pressure medication has &lt;b&gt;an effect&lt;/b&gt; on the average blood pressure of heart patients. What are the hypotheses?
]

---

class: middle

# Testing for independence

---

## Is yawning contagious?

.question[
Do you think yawning is contagious?
]

.pull-left[
![](img/yawn1.png)
]
.pull-right[
![](img/yawn2.png)
]

---

## Is yawning contagious?

An experiment conducted by the MythBusters tested if a person can be subconsciously influenced into yawning if another person near them yawns.

https://www.discovery.com/tv-shows/mythbusters/videos/is-yawning-contagious-2

---

## Study description

In this study 50 people were randomly assigned to two groups: 34 to a group where a person near them yawned (treatment) and 16 to a control group where they didn't see someone yawn (control).

The data are in the **openintro** package: `yawn`


```r
yawn %&gt;%
  count(group, result)
```

```
## # A tibble: 4 × 3
##   group result       n
##   &lt;fct&gt; &lt;fct&gt;    &lt;int&gt;
## 1 ctrl  not yawn    12
## 2 ctrl  yawn         4
## 3 trmt  not yawn    24
## 4 trmt  yawn        10
```

---

## Proportion of yawners

.small[

```r
yawn %&gt;%
  count(group, result) %&gt;%
  group_by(group) %&gt;%
  mutate(p_hat = n / sum(n))
```

```
## # A tibble: 4 × 4
## # Groups:   group [2]
##   group result       n p_hat
##   &lt;fct&gt; &lt;fct&gt;    &lt;int&gt; &lt;dbl&gt;
## 1 ctrl  not yawn    12 0.75 
## 2 ctrl  yawn         4 0.25 
## 3 trmt  not yawn    24 0.706
## 4 trmt  yawn        10 0.294
```
]

- Proportion of yawners in the treatment group: `\(\frac{10}{34} = 0.2941\)`
- Proportion of yawners in the control group: `\(\frac{4}{16} = 0.25\)`
- Difference: `\(0.2941 - 0.25 = 0.0441\)`
- Our results match the ones calculated on the MythBusters episode.

---

## Independence?

.question[
Based on the proportions we calculated, do you think yawning is really contagious, i.e. are seeing someone yawn and yawning dependent?
]


```
## # A tibble: 4 × 4
## # Groups:   group [2]
##   group result       n p_hat
##   &lt;fct&gt; &lt;fct&gt;    &lt;int&gt; &lt;dbl&gt;
## 1 ctrl  not yawn    12 0.75 
## 2 ctrl  yawn         4 0.25 
## 3 trmt  not yawn    24 0.706
## 4 trmt  yawn        10 0.294
```

---

## Dependence, or another possible explanation?

- The observed differences might suggest that yawning is contagious, i.e. seeing someone yawn and yawning are dependent.

- But the differences are small enough that we might wonder if they might simple be **due to chance**.

- Perhaps if we were to repeat the experiment, we would see slightly different results.

- So we will do just that - well, somewhat - and see what happens.

- Instead of actually conducting the experiment many times, we will **simulate** our results.

---

## Two competing claims

- "There is nothing going on." 
Yawning and seeing someone yawn are **independent**, yawning is not contagious, observed difference in proportions is simply due to chance. `\(\rightarrow\)` Null hypothesis

- "There is something going on."
Yawning and seeing someone yawn are **dependent**, yawning is contagious, observed difference in proportions is not due to chance. `\(\rightarrow\)` Alternative hypothesis

---

## Simulation setup

1. A regular deck of cards is comprised of 52 cards: 4 aces, 4 of numbers 2-10, 4 jacks, 4 queens, and 4 kings.

2. Take out two aces from the deck of cards and set them aside.

3. The remaining 50 playing cards to represent each participant in the study:
    - 14 face cards (including the 2 aces) represent the people who yawn.
    - 36 non-face cards represent the people who don't yawn.

---

## Running the simulation

1. Shuffle the 50 cards at least 7 times&lt;sup&gt;1&lt;/sup&gt; to ensure that the cards counted out are from a random process.

2. Count out the top 16 cards and set them aside. These cards represent the people in the control group.

3. Out of the remaining 34 cards (treatment group) count the \red{number of face cards} (the number of people who yawned in the treatment group).

4. Calculate the difference in proportions of yawners (treatment - control), and plot it 
on the board.

5. Mark the difference you find on the dot plot on the board.

.footnote[
[1] http://www.dartmouth.edu/~chance/course/topics/winning_number.html
]

---

## Simulation by hand

.question[
Do the simulation results suggest that yawning is contagious, i.e. does seeing someone yawn and yawning appear to be dependent?
]

![yawn-sim-results](img/yawn-sim-results.png)

---

## Simulation by computation


```r
null_dist &lt;- yawn %&gt;%
  specify(response = result, explanatory = group, 
          success = "yawn") %&gt;%
  hypothesize(null = "independence") %&gt;%
  generate(100, type = "permute") %&gt;%
  calculate(stat = "diff in props", 
            order = c("trmt", "ctrl"))
```

---

## Simulation by computation - 1

.small[
- Start with the data frame
- **Specify the variables**
    - **Since the response variable is categorical, specify the level which should be considered as "success"**


```r
yawn %&gt;%
{{  specify(response = result, explanatory = group, 
          success = "yawn") }}
```
]

---

## Simulation by computation - 2

.small[
- Start with the data frame
- Specify the variables
    - Since the response variable is categorical, specify the level which should be considered as "success"
- **State the null hypothesis (yawning and whether or not you see someone yawn are independent)**


```r
yawn %&gt;%
  specify(response = result, explanatory = group, 
          success = "yawn") %&gt;%
* hypothesize(null = "independence") 
```
]

---

## Simulation by computation - 3

.small[
- Start with the data frame
- Specify the variables
    - Since the response variable is categorical, specify the level which should be considered as "success"
- State the null hypothesis (yawning and whether or not you see someone yawn are independent)
- **Generate simulated differences via permutation**


```r
yawn %&gt;%
  specify(response = result, explanatory = group, 
          success = "yawn") %&gt;%
  hypothesize(null = "independence") %&gt;%
* generate(100, type = "permute") 
```
]

---

## Simulation by computation - 4

.small[
- Start with the data frame
- Specify the variables
    - Since the response variable is categorical, specify the level which should be considered as "success"
- State the null hypothesis (yawning and whether or not you see someone yawn are independent)
- Generate simulated differences via permutation
- **Calculate the sample statistic of interest (difference in propotions)**
    - **Since the explanatory variable is categorical, specify the order in which the subtraction should occur for the calculation of the sample statistic, `\((\hat{p}_{treatment} - \hat{p}_{control})\)`.**
    

```r
yawn %&gt;%
  specify(response = result, explanatory = group, 
          success = "yawn") %&gt;%
  hypothesize(null = "independence") %&gt;%
  generate(100, type = "permute") %&gt;%
{{ calculate(stat = "diff in props", 
           order = c("trmt", "ctrl")) }}
```
]

---

## Simulation by computation - 0

.small[
- **Save the result**
- Start with the data frame
- Specify the variables
    - Since the response variable is categorical, specify the level which should be considered as "success"
- State the null hypothesis (yawning and whether or not you see someone yawn are independent)
- Generate simulated differences via permutation
- Calculate the sample statistic of interest (difference in propotions)
    - Since the explanatory variable is categorical, specify the order in which the subtraction should occur for the calculation of the sample statistic, `\((\hat{p}_{treatment} - \hat{p}_{control})\)`.
    

```r
*null_dist &lt;- yawn %&gt;% 
  specify(response = outcome, explanatory = group, 
          success = "yawn") %&gt;%
  hypothesize(null = "independence") %&gt;%
  generate(100, type = "permute") %&gt;%
  calculate(stat = "diff in props", 
            order = c("treatment", "control"))
```
]

---

## Visualizing the null distribution

.question[
What would you expect the center of the null distribution to be?
]

--


```r
ggplot(data = null_dist, mapping = aes(x = stat)) +
  geom_histogram(binwidth = 0.05) +
  labs(title = "Null distribution")
```

&lt;img src="u4-d12-hypothesis-testing_files/figure-html/unnamed-chunk-24-1.png" width="70%" style="display: block; margin: auto;" /&gt;

---

## Calculating the p-value, visually

.question[
What is the p-value, i.e. in what % of the 
simulations was the simulated difference in sample proportion at least as extreme 
as the observed difference in sample proportions?
]

&lt;img src="u4-d12-hypothesis-testing_files/figure-html/unnamed-chunk-25-1.png" width="80%" style="display: block; margin: auto;" /&gt;

---

## Calculating the p-value, directly


```r
null_dist %&gt;%
  filter(stat &gt;= 0.0441) %&gt;%
  summarise(p_value = n()/nrow(null_dist))
```

```
## # A tibble: 1 × 1
##   p_value
##     &lt;dbl&gt;
## 1    0.53
```

---

## Conclusion

.question[
What is the conclusion of the hypothesis test?
]

&lt;br&gt;

--

.question[
Do you "buy" this conclusion?
]
    </textarea>
<style data-target="print-only">@media screen {.remark-slide-container{display:block;}.remark-slide-scaler{box-shadow:none;}}</style>
<script src="https://remarkjs.com/downloads/remark-latest.min.js"></script>
<script>var slideshow = remark.create({
"ratio": "16:9",
"highlightLines": true,
"highlightStyle": "solarized-light",
"countIncrementalSlides": false
});
if (window.HTMLWidgets) slideshow.on('afterShowSlide', function (slide) {
  window.dispatchEvent(new Event('resize'));
});
(function(d) {
  var s = d.createElement("style"), r = d.querySelector(".remark-slide-scaler");
  if (!r) return;
  s.type = "text/css"; s.innerHTML = "@page {size: " + r.style.width + " " + r.style.height +"; }";
  d.head.appendChild(s);
})(document);

(function(d) {
  var el = d.getElementsByClassName("remark-slides-area");
  if (!el) return;
  var slide, slides = slideshow.getSlides(), els = el[0].children;
  for (var i = 1; i < slides.length; i++) {
    slide = slides[i];
    if (slide.properties.continued === "true" || slide.properties.count === "false") {
      els[i - 1].className += ' has-continuation';
    }
  }
  var s = d.createElement("style");
  s.type = "text/css"; s.innerHTML = "@media print { .has-continuation { display: none; } }";
  d.head.appendChild(s);
})(document);
// delete the temporary CSS (for displaying all slides initially) when the user
// starts to view slides
(function() {
  var deleted = false;
  slideshow.on('beforeShowSlide', function(slide) {
    if (deleted) return;
    var sheets = document.styleSheets, node;
    for (var i = 0; i < sheets.length; i++) {
      node = sheets[i].ownerNode;
      if (node.dataset["target"] !== "print-only") continue;
      node.parentNode.removeChild(node);
    }
    deleted = true;
  });
})();
// add `data-at-shortcutkeys` attribute to <body> to resolve conflicts with JAWS
// screen reader (see PR #262)
(function(d) {
  let res = {};
  d.querySelectorAll('.remark-help-content table tr').forEach(tr => {
    const t = tr.querySelector('td:nth-child(2)').innerText;
    tr.querySelectorAll('td:first-child .key').forEach(key => {
      const k = key.innerText;
      if (/^[a-z]$/.test(k)) res[k] = t;  // must be a single letter (key)
    });
  });
  d.body.setAttribute('data-at-shortcutkeys', JSON.stringify(res));
})(document);
(function() {
  "use strict"
  // Replace <script> tags in slides area to make them executable
  var scripts = document.querySelectorAll(
    '.remark-slides-area .remark-slide-container script'
  );
  if (!scripts.length) return;
  for (var i = 0; i < scripts.length; i++) {
    var s = document.createElement('script');
    var code = document.createTextNode(scripts[i].textContent);
    s.appendChild(code);
    var scriptAttrs = scripts[i].attributes;
    for (var j = 0; j < scriptAttrs.length; j++) {
      s.setAttribute(scriptAttrs[j].name, scriptAttrs[j].value);
    }
    scripts[i].parentElement.replaceChild(s, scripts[i]);
  }
})();
(function() {
  var links = document.getElementsByTagName('a');
  for (var i = 0; i < links.length; i++) {
    if (/^(https?:)?\/\//.test(links[i].getAttribute('href'))) {
      links[i].target = '_blank';
    }
  }
})();
// adds .remark-code-has-line-highlighted class to <pre> parent elements
// of code chunks containing highlighted lines with class .remark-code-line-highlighted
(function(d) {
  const hlines = d.querySelectorAll('.remark-code-line-highlighted');
  const preParents = [];
  const findPreParent = function(line, p = 0) {
    if (p > 1) return null; // traverse up no further than grandparent
    const el = line.parentElement;
    return el.tagName === "PRE" ? el : findPreParent(el, ++p);
  };

  for (let line of hlines) {
    let pre = findPreParent(line);
    if (pre && !preParents.includes(pre)) preParents.push(pre);
  }
  preParents.forEach(p => p.classList.add("remark-code-has-line-highlighted"));
})(document);</script>

<script>
slideshow._releaseMath = function(el) {
  var i, text, code, codes = el.getElementsByTagName('code');
  for (i = 0; i < codes.length;) {
    code = codes[i];
    if (code.parentNode.tagName !== 'PRE' && code.childElementCount === 0) {
      text = code.textContent;
      if (/^\\\((.|\s)+\\\)$/.test(text) || /^\\\[(.|\s)+\\\]$/.test(text) ||
          /^\$\$(.|\s)+\$\$$/.test(text) ||
          /^\\begin\{([^}]+)\}(.|\s)+\\end\{[^}]+\}$/.test(text)) {
        code.outerHTML = code.innerHTML;  // remove <code></code>
        continue;
      }
    }
    i++;
  }
};
slideshow._releaseMath(document);
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src  = 'https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-MML-AM_CHTML';
  if (location.protocol !== 'file:' && /^https?:/.test(script.src))
    script.src  = script.src.replace(/^https?:/, '');
  document.getElementsByTagName('head')[0].appendChild(script);
})();
</script>
  </body>
</html>
